<!-- Dom模板 -->
<template>
  <div class="shoppingMain">
    <!-- Dom内容 -->
    <!-- 购物车标题 -->
    <div class="shoppingTitleDiv" v-if="carData.length>0">
      <p>
          <i class="iconfont icon-zuojiantou-01" @click="turnBacks"></i>
        购物车<span>({{ carData.length }})</span>
      </p>
      
      <p v-if="!manageFlag" @click="manageClick">管理</p>
      <p v-if="manageFlag" class="manageP" @click="closemanageFlag">
        <span>管理</span>
        <i class="iconfont icon-guanbi-01" style="font-size: 12px"></i>
      </p>
    </div>
    <!-- 空状态 -->
    <van-empty description="购物车空空如也~" v-if="carData.length<=0"/>
    <!-- 商品内容详情 -->
    <div class="shoppingCon" @touchmove="noShowUL" ref="contentAll" v-if="carData.length>0">
      <van-pull-refresh v-model="isLoading" @refresh="onRefreshs">
        <van-checkbox-group v-model="result" ref="checkboxGroup">
          <div class="contents" v-for="(item, index) in carData" :key="index">
            <van-checkbox
              checked-color="#ee0a24"
              :name="item.goods_id"
              @click="checkedChange(item, index)"
            />

            <p class="contentsP">
              <img :src="item.goods_url" alt="" @click="turnCarDetail(item)" />
            </p>
            <div class="detailsDiv">
              <p class="titleP" @click="turnCarDetail(item)">
                {{ item.goods_name }}
              </p>
              <div class="marg typeDiv">
                <span>15ml</span>
              </div>
              <p class="red fontFour marg">限时特惠</p>
              <div class="changeDiv">
                <p class="red">
                  ￥<span>{{ item.price }}</span>
                </p>
                <ul v-if="item.flag">
                  <li @click="changeNum(false, item.goods_id)">-</li>
                  <li>{{ item.goods_number }}</li>
                  <li @click="changeNum(true, item.goods_id)">+</li>
                </ul>
                <button v-if="!item.flag" @click="showUL(item)">
                  x{{ item.goods_number }}
                </button>
              </div>
            </div>
          </div>
        </van-checkbox-group>
      </van-pull-refresh>
    </div>
    <!-- 底部小计栏 -->
    <div v-if="!manageFlag" class="bottomCon">
      <div class="btm">
        <p class="checkAllP">
          <van-checkbox
            name="b"
            v-model="checkAlls"
            checked-color="#ee0a24"
            @click="toggleAll"
          />全选
          <!-- <label for="checkAllLabel"></label>  id="checkAllLabel" -->
        </p>
        <div class="settlementDiv">
          <div style="display: flex">
            <p>已选{{ num }}件</p>
            <p>
              合计：<span class="red">￥{{ price }}</span>
            </p>
          </div>
          <p class="fonts">已优惠<span class="red">￥0.00</span></p>
        </div>
      </div>
      <button class="settlementButton" @click="openConfirmOrder">结算({{ num }})</button>
    </div>
    <!-- 底部操作栏 -->
    <div v-if="manageFlag" class="bottomCon">
      <div
        class="btm"
        style="width: 100vw; justify-content: space-between; padding: 0 14px"
      >
        <p class="checkAllP">
          <van-checkbox
            name="b"
            v-model="checkAlls"
            checked-color="#ee0a24"
            @click="toggleAll"
          />全选
        </p>
        <div class="settlementDivTwo">
          <button @click="addLikes">移入收藏夹</button>
          <button @click="delShop">删除</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import a from './a'; // 引入组件
import * as apis from "../../../components/api/shopping_yqq";

export default {
  name: "",
  data() {
    return {
      msg: "测试",
      result: [],
      manageFlag: false, // 点击管理
      ulFlag: false, // 加减操作
      carData: [], // 购物车数据
      num: 0, // 选中的商品的数量
      price: 0, // 选中的商品的价格
      isLoading: false, // 下拉刷新
      checkArr:[], // 选中的数组
    };
  },

  // 监听属性
  computed: {
    checkAlls: {
      get() {
        return this.carData.every(item => {
          return item.goods_checked;
        });
      },
      set(val) {
        console.log(val);
        apis
          .chooseShop({
            uid: JSON.parse(localStorage.getItem("token")).uid,
            val,
          })
          .then((res) => {
            // console.log(res);
            this.carData = res.data.map((item) => {
              item.flag = false;
              item.goods_checked = JSON.parse(item.goods_checked);
              return item;
            });
            this.getCarData();
          });
      },
    },
  },
  // 组件挂载的地方
  components: {},
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.getCarData();
  },
  // Vue方法定义
  methods: {
    // 添加商品到收藏夹
    addLikes() {
      console.log(this.result);
      apis
        .changeShopsTypes({
          type: "02",
          uid: JSON.parse(localStorage.getItem("token")).uid,
          result: this.result,
        })
        .then((res) => {
          this.getCarData();
          this.$toast.success('移入收藏夹成功');
        });
    },
    // 获取购物车数据
    getCarData(id) {
      apis
        .getCarData({ uid: JSON.parse(localStorage.getItem("token")).uid })
        .then((res) => {
          this.result = [];
          this.checkArr = [];
          console.log(res);
          this.carData = res.data.map((item) => {
            item.flag = false;
            if (item.goods_id == id) {
              item.flag = true;
            }

            item.goods_checked = JSON.parse(item.goods_checked);
            if (item.goods_checked) {
              this.result.push(item.goods_id);
            }
            return item;
          })

          this.price = res.price;
          this.num = res.num;
          localStorage.setItem('carLength',this.carData.length)

          this.carData.forEach(item=>{
            if(item.goods_checked){
              this.checkArr.push(item);
            }
          })
          this.$store.commit('yanqq/getCheckArrAndPrices',{checkArr:this.checkArr, prices:this.price})

        });
    },
    // 打开、关闭弹窗      点击结算
    openConfirmOrder() {
      // 判断有没有选中的商品
      if (this.result.length > 0) {
        this.$router.push("/confirmOrder");
      } else {
        this.$toast({
          message: "您还没有选择宝贝哦！",
          position: "bottom"
        });
      }
    },
    // 全选反选
    toggleAll() {
      this.$refs.checkboxGroup.toggleAll(!this.checkAlls);
    },
    // 点击管理
    manageClick() {
      // 让底部信息栏修改为移入收藏夹 删除这些操作
      this.manageFlag = true;
    },
    closemanageFlag() {
      this.manageFlag = false;
    },
    // 改变加减的样式
    showUL(item) {
      item.flag = true;
    },
    noShowUL() {
      this.carData = this.carData.map(item => {
        item.flag = false;
        return item;
      });
    },
    // 加减数量时间
    changeNum(flag, id) {
      apis
        .changeShopsTypes({
          type: "03",
          uid: JSON.parse(localStorage.getItem("token")).uid,
          id,
          flag,
        })
        .then((res) => {
          this.getCarData(id);
        });
    },
    turnCarDetail(item) {
      // 跳转到(购物车)此商品详情
      this.$router.push({ path: "/details", query: { ...item } });
    },
    // 选中状态
    async checkedChange(item, i) {
      // 提交给结算的数据
      let res = await apis.shopp(this.carData[i]);
      let ind = this.result.indexOf(item.goods_id);
      if (ind) {
        this.result.splice(ind, 1);
      } else {
        this.result.push(item.goods_id);
      }
      this.getCarData();
    },
    // 下拉刷新
    onRefreshs() {
      if (this.$refs["contentAll"].scrollTop === 0) {
        this.onRefresh();
      } else {
        this.isLoading = false;
      }
    },
    onRefresh() {
      this.getCarData();
      setTimeout(() => {
        this.$toast("刷新成功");
        this.isLoading = false;
      }, 1000);
    },
    // 删除商品
    delShop() {
      // 判断有没有选中的商品
      if (this.result.length > 0) {
        this.$dialog.confirm({
          title: '提示',
          message: '确定从购物车删除此商品吗',
        })
          .then(() => {apis
            .changeShopsTypes({
              type: "01",
              uid: JSON.parse(localStorage.getItem("token")).uid,
              result: this.result,
            })
            .then((res) => {
              this.getCarData();
              this.$toast.success('已删除');
            });
          })
          .catch(() => {
            this.$toast("已取消");
          });
        
        console.log("删除");
      } else {
        this.$toast({
          message: "您还没有选择宝贝哦！",
          position: "bottom",
        });
      }
    },
    // 返回
    turnBacks(){
        this.$router.history.go(-1);
    }
  },
};
</script>

<style>
.van-toast--bottom {
  bottom: 7% !important;
}
.van-toast--text {
  padding: 4px 12px;
}

</style>

<style scoped>
/* @import url(''); 引入css类 */
@import url("../../../components/fonts/iconfont.css");

.shoppingMain {
  position: fixed;
  z-index: 7;
  height: 100vh;
  background-color: #f5f5f5;
}
/* 标题 */
.shoppingTitleDiv {
  width: 100vw;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  box-sizing: border-box;
  padding: 14px;
}
.shoppingTitleDiv span {
  font-size: 14px;
}
.shoppingTitleDiv p + p {
  font-size: 15px;
}
.manageP {
  display: flex;
  width: 15%;
  padding: 0 4px;
  color: salmon;
  border: 1px solid salmon;
  border-radius: 10px;
  align-items: center;
  justify-content: space-between;
}

/* 中间内容 */
.shoppingCon {
  height: calc(100vh - 5.9rem);
  overflow-y: auto;
}
.contents {
  display: flex;
  width: 100vw;
  margin-bottom: 10px;
  padding: 10px;
  box-sizing: border-box;
  background-color: #fff;
  justify-content: space-around;
}
.contentsP input {
  margin: 6px;
}
.contentsP {
  display: flex;
  align-items: center;
}
.contentsP img {
  width: 100px;
  height: 100px;
  vertical-align: middle;
}
.detailsDiv {
  width: 212px;
  font-size: 14px;
}
.typeDiv span {
  background-color: #eaeaea;
  display: inline-block;
  padding: 2px 4px;
}
.changeDiv {
  display: flex;
  justify-content: space-between;
}
.changeDiv ul {
  display: flex;
  align-items: center;
  border: 1px solid #acacac;
  justify-content: space-around;
}
ul li {
  height: 20px;
  line-height: 20px;
  padding: 0px 10px;
  color: #acacac;
}
ul li:nth-child(2) {
  color: #6a6a6a;
  padding: 0px 12px;
  border-left: 1px solid #acacac;
  border-right: 1px solid #acacac;
}

/* 公共样式 */
.red {
  color: red;
}
.fontFour {
  font-size: 14px;
}
.marg {
  margin: 2px 0;
}

/* 底部 */
.bottomCon {
    display: flex;
    width: 100vw;
    height: 49px;
    position: fixed;
    top: calc(100vh - 3.093rem);
    background-color: #fff;
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
}
.btm {
  width: calc(100vw - 110px);
  display: flex;
  align-items: center;
  justify-content: space-around;
}
.btm p:nth-child(1) {
  font-size: 15px;
}
.btm p:nth-child(1) input {
  margin-right: 2px;
  vertical-align: middle;
}
.settlementDiv {
  max-width: 200px;
  text-align: center;
}
.settlementButton {
  color: #fff;
  width: 110px;
  height: 49px;
  outline: none;
  border: 0;
  right: 0px;
  font-size: 15px;
  position: absolute;
  background-color: red;
  /* border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc; */
}
.settlementDivTwo button {
  color: salmon;
  border: 2px solid salmon;
  border-radius: 20px;
  padding: 3px 8px;
  font-size: 14px;
  background-color: #fff;
}
.settlementDivTwo button:nth-child(1) {
  color: #ffc532;
  border-color: #ffc532;
}

.checkAllP {
  width: 54px;
  display: flex;
  justify-content: space-between;
}


.fonts {
  font-size: 14px;
}
</style>
